# load configuration
begin
  if $CONFIG_FILE
    conf_file = $CONFIG_FILE
  else
    conf_file = etc_conf = "/etc/yarbo/config.yml"
    unless File.exists? conf_file 
      # can use local config.yml file in case we're running non-gem installation
      conf_file = File.dirname(File.expand_path(__FILE__))+"/../../config.yml"
    end
  end

  unless File.exists? conf_file  
    require 'fileutils'
    
    example_conf_file = File.expand_path(File.dirname(File.expand_path(__FILE__))+"/../../config.example.yml")
    puts "\nYARBO NOT YET CONFIGURED!!!\n"
    puts "\nAttempting to copy sample configuration from '#{example_conf_file}' to '#{etc_conf}'...\n"
    
    unless File.exists? example_conf_file
      puts "\nFor some strange reason the template configuration file '#{example_conf_file}' does not exist!" +
        " The default configuration file cannot be created... you'll have to create the configuration manually.\n\n"
      exit 2
    end
    
    begin
      FileUtils.mkdir("/etc/yarbo") unless File.exists? "/etc/yarbo"
      FileUtils.cp(example_conf_file, etc_conf)
    rescue Errno::EACCES
      puts "\nIt appears that you do not have permissions to create the '#{etc_conf}' file. Try running this command as root (i.e. usin sudo).\n"
      exit 2
    rescue
      puts "\nFor some reason the '#{etc_conf}' file could not be created. You'll have to copy the file manually." +
        " Use '#{example_conf_file}' as a template.\n"
      exit 2
    end
    
    puts "\nA sample configuration has been created for you in '#{etc_conf}'. Please edit this file to" +
      " suit your needs and then run yarbo again.\n"
    exit 1
  end
  
  
  loaded_conf = HashWithIndifferentAccess.new(YAML.load_file(conf_file))
  
  if $CONF
    $CONF = loaded_conf.merge $CONF
  else
    $CONF = loaded_conf
  end
  
rescue
    raise "Your Yarbo configuration may be invalid."+
      " Please double-check check your config.yml file."+
      " Make sure that you are using spaces instead of tabs for your indentation!!" +
      "\n\nUNDERLYING EXCEPTION:\n#{$!}"
end

module Yarbo
  module Conf
    DEFAULTS = {
      :log => {:file => 'yarbo.log', :level => 'DEBUG'},
      :uri_path => "/"
    }
  
    def [](key)
      $CONF[key] || DEFAULTS[key]
    end
    module_function "[]".intern
    
    def self.method_missing(method, *args)
      self[method]
    end
  end
end
